import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { addPost, updatePost } from "@/api/flandre-ui/request";
import { message } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
const PostDrawer = (props: { register: Fn; reload: Fn }) => {
	const { t } = useTranslation();
	const en_vi = "HRMS.postManagement";
	const [action, setAction] = useState(""); // 用来区分新增还是修改
	const [currentPkId, setCurrentPkId] = useState("");

	const postFormSchema: FormSchema[] = [
		{
			label: t(`${en_vi}.jobPositionType`),
			field: "jobpozType",
			component: "Input",
			colProps: { span: 24 }
		},
		{
			label: t(`${en_vi}.definitionCN`),
			field: "definitionCn",
			component: "Input",
			colProps: { span: 24 }
		},
		{
			label: t(`${en_vi}.definitionEN`),
			field: "definitionEn",
			component: "Input",
			colProps: { span: 24 }
		},
		{
			label: t(`${en_vi}.definitionVI`),
			field: "definitionVi",
			component: "Input",
			colProps: { span: 24 }
		},
		{
			label: t(`${en_vi}.supplementaryExplanation`),
			field: "definitionExp",
			component: "Input",
			colProps: { span: 24 }
		}
	];

	const [registerForm, { validateFields, resetFields, setFieldsValue }] = useForm({
		labelWidth: 120,
		schemas: postFormSchema,
		showActionButtonGroup: false
	});

	const [registerDrawer, { closeDrawer }] = useDrawerInner(props.register, data => {
		resetFields();
		const record = data.record || {};
		setAction(data.action || "add");
		if (data.action === "edit") {
			setCurrentPkId(record.jobpozId);
			setFieldsValue(record);
		}
	});

	async function handleSubmit() {
		try {
			const values = await validateFields();
			if (action === "edit") {
				values.jobpozId = currentPkId;
				await updatePost(values);
				message.success(t("kevin_ui.updateSuccess"));
			} else {
				await addPost(values);
				message.success(t("kevin_ui.addedSuccessfully"));
			}
			props.reload();
			closeDrawer();
		} catch (error) {
			message.error(t("kevin_ui.operationFailed"));
		}
	}

	return (
		<BasicDrawer {...props} title={action === "edit" ? "Edit Post" : "Add Post"} register={registerDrawer} ok={handleSubmit}>
			<BasicForm register={registerForm} />
		</BasicDrawer>
	);
};

export default PostDrawer;
